package packed_widgets

import (
	"file_explorer/model"
	"file_explorer/service/eventbus"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

type Table struct {
	*BaseComponent
	*widget.Table
	Checklist *Checklist

	columns       []*TableColumn
	getData       func(index int) interface{}
	getDataLength func() int

	orderColumn int
	orderAsc    bool

	OnDoubleTapped func(row int, col int)
}

// 重置数据、还原顺序、重新初始化选中项，只刷新数据用Refresh
func (table *Table) Reset() {
	if len(table.columns) > 0 && table.columns[table.orderColumn].OrderBy != nil {
		table.columns[table.orderColumn].OrderBy(table.orderAsc)
	}
	table.Table.Refresh()
	table.ScrollToTop()

	table.Checklist.Reset(table.getDataLength())
}

func (table *Table) GetContent(row int, col int) string {
	if table.columns[col].GetText == nil {
		return ""
	}

	return table.columns[col].GetText(table.getData(row))
}

func (table *Table) SetGetData(getData func(int) interface{}) {
	table.getData = getData
}

func (table *Table) SetGetDataLength(getDataLength func() int) {
	table.getDataLength = getDataLength
}

func (table *Table) AddColumn(column *TableColumn) {
	table.columns = append(table.columns, column)
}

func (table *Table) Build() {
	table.Table = widget.NewTableWithHeaders(nil, nil, nil)

	table.Table.CreateHeader = func() fyne.CanvasObject {
		return container.NewHBox(
			widget.NewCheck("", nil),
			NewLabel(""),
		)
	}

	table.Table.UpdateHeader = func(cell widget.TableCellID, obj fyne.CanvasObject) {
		// 提取组件
		cellContainer := obj.(*fyne.Container)
		checkBox := cellContainer.Objects[0].(*widget.Check)
		label := cellContainer.Objects[1].(*Label)

		// 第一列
		if cell.Col < 0 {
			checkBox.Show()
			// checkBox与checklist状态同步，手动点击checkbox本体触发
			checkBox.OnChanged = func(b bool) {
				table.Checklist.Check(cell.Row, b)
			}

			// 初始checklist状态同步checkbox，手动写入避免触发onChanged
			checkBox.Checked = table.Checklist.GetCheckStatus(cell.Row)
			checkBox.Refresh()

			label.Hide()
			cellContainer.Refresh()
			return
		}

		// 第一行
		if cell.Row < 0 {
			checkBox.Hide()

			if table.orderColumn == cell.Col {
				if table.orderAsc {
					label.SetText(table.columns[cell.Col].Header + " ↑")
				} else {
					label.SetText(table.columns[cell.Col].Header + " ↓")
				}
			} else {
				label.SetText(table.columns[cell.Col].Header)
			}
			// 点击header时排序
			label.OnTapped = func() {
				if table.columns[cell.Col].OrderBy == nil {
					return
				}

				if table.orderColumn != cell.Col {
					// 切换排序列
					table.orderColumn = cell.Col
					table.orderAsc = true
				} else {
					// 切换顺序
					table.orderAsc = !table.orderAsc
				}
				// 调用newTable时定义的排序方法
				table.columns[cell.Col].OrderBy(table.orderAsc)
				table.ProduceEvent(eventbus.EventKeyWidgetTableOrderChange, nil)
				table.Refresh()
			}

			cellContainer.Refresh()
			return
		}

	}

	table.Table.Length = func() (int, int) {
		return table.getDataLength(), len(table.columns)
	}

	table.Table.CreateCell = func() fyne.CanvasObject {
		return container.NewHBox(
			widget.NewIcon(nil),
			NewLabel(""),
		)
	}

	table.Table.UpdateCell = func(cell widget.TableCellID, obj fyne.CanvasObject) {
		// 提取组件
		cellContainer := obj.(*fyne.Container)

		icon := cellContainer.Objects[0].(*widget.Icon)
		label := cellContainer.Objects[1].(*Label)

		// 设置文本
		label.SetTextWithFixWidth(
			table.GetContent(cell.Row, cell.Col),
			cellContainer.Size().Width)
		label.Resize(cellContainer.Size())

		label.OnTapped = func() {
			// 单击切换选中状态
			if table.Checklist != nil {
				table.Checklist.Toggle(cell.Row)
			}
		}

		// 设置cell双击事件
		label.OnDoubleTapped = func() {
			// 双击展开优先
			if table.columns[cell.Col].DoubleTappedExpand {
				popUp := NewPopUp(400, 200)

				textEntry := widget.NewEntry()
				textEntry.Text = table.GetContent(cell.Row, cell.Col)
				textEntry.MultiLine = true
				textEntry.Wrapping = fyne.TextWrapBreak //自动换行
				textEntry.OnSubmitted = func(text string) {
					table.ProduceEvent(eventbus.EventKeyWidgetTableExpandCellEntrySubmit, map[string]interface{}{
						"data": table.getData(cell.Row),
						"key":  table.columns[cell.Col].Key,
						"text": text,
					})
					textEntry.Hide()
					popUp.Hide()
				}

				popUp.Show(textEntry, obj)
				return
			}

			// 未设置双击展开，触发table双击事件
			if table.OnDoubleTapped != nil {
				table.OnDoubleTapped(cell.Row, cell.Col)
			}
		}

		// 设置icon
		if table.columns[cell.Col].GetIcon == nil {
			icon.Hide()
		} else {
			icon.Resource = table.columns[cell.Col].GetIcon(table.getData(cell.Row))
			icon.Show()
		}
		icon.Refresh() // 不加刷新容易显示不全

	}

	for i, column := range table.columns {
		table.SetColumnWidth(i, float32(column.Width))
		if column.DefaultOrderBy {
			table.orderColumn = i
		}
	}

	table.Reset()
	table.ExtendBaseWidget(table)

	table.Checklist.RegisterConsumer(eventbus.EventKeyWidgetChecklistChange, func(event *model.Event) {
		table.Refresh()
	})
}

func NewTable() *Table {
	table := &Table{
		BaseComponent: NewBaseComponent(),
		Checklist:     NewChecklist(),
		orderAsc:      true,
	}

	return table
}
